package top.lyc829.leetcode.test;

import java.util.ArrayList;

public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        quickSort(input, 0, input.length - 1);
        for (int i = 0; i < k; i++) {
            result.add(input[i]);
        }
        return result;
    }

    private void quickSort(int[] input, int left, int right) {
        if (right >= left) return;
        int x = input[left];
        int i = left;
        int j = right;
        while(i < j) {
            while(i < j && input[j] > x) {
                j--;
            }
            if (i < j) {
                input[i++] = input[j];
            }
            while(i < j && input[i] < x) {
                i++;
            }
            if (i < j) {
                input[j--] = input[i];
            }
        }
        input[i] = x;
        quickSort(input, left, i - 1);
        quickSort(input, i + 1, right);
    }

    private void quickSort2(int[] arr, int left, int right) {
        if (left >= right) {
            return;
        }

        int i = left;
        int j = right;
        int x = arr[left];

        while(i < j) {
            while (i < j && arr[j] > x) {
                j--;
            }
            if (i < j) {
                arr[i++] = arr[j];
            }

            while(i < j && arr[i] < x) {
                i++;
            }
            if (i < j) {
                arr[j--] = arr[i];
            }
        }
        arr[i] = x;
        quickSort(arr, left, i - 1);
        quickSort(arr, i + 1, right);

    }
}